/*
 * @Author: your name
 * @Date: 2021-06-03 17:21:23
 * @LastEditTime: 2021-06-03 17:23:31
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bazai_island_api\app\models\hot-book.js
 */
const { Sequelize, Model, Op } = require('sequelize')
const { sequelize } = require('@core/mysqlDB')
const { Favor } = require('@models/favor')


class HotBook extends Model {
  // 查询所有热门书籍
  static async getAll() {
    const books = await HotBook.findAll({
      order: [
        'index'
      ]
    })
    const ids = []
    // 存储id
    books.forEach((book) => {
      ids.push(book.id)
    })
    const favors = await Favor.findAll({
      // 查询条件
      where: {
        art_id: {
          [Op.in]: ids
        }
      },
      // 分组
      group: ['art_id'],
      // 求和返回的字段名称 
      attributes: ['art_id', [Sequelize.fn('COUNT', '*'), 'count']]
    })
    books.forEach(book => {
      HotBook._getEachBookStatus(book, favors)
    })
    return books
  }
  // 计算喜爱的数量
  static _getEachBookStatus(book, favors) {
    let count = 0
    favors.forEach(favor => {
      if (book.id === favor.art_id) {
        count = favor.get('count')
      }
    })
    book.setDataValue('count', count)
    return book
  }
}

HotBook.init({
    index: Sequelize.INTEGER,
    image: Sequelize.STRING,
    author: Sequelize.STRING,
    title: Sequelize.STRING,
}, {
  sequelize,
  tableName: 'hot_book'
})
// index: 排序

module.exports = {
  HotBook
}